package com.google.code.jcooky.rpc.server;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

public class ServiceExecutor {
	private Class<?> returnType;
	private Object returnValue;
	
	public void execute(Object service, String methodName, List<Object> args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		Class<?> []parameterTypes = null;
		Object []parameters = null;
		if(!args.isEmpty()) { /** argument not void */
			final int size = args.size();
			parameterTypes = new Class<?>[size];
			parameters = new Object[size];
			
			for(int i = 0 ; i < size ; ++i) {
				Object arg = args.get(i);
				parameterTypes[i] = arg.getClass();
				parameters[i] = arg;
			}
		}
		
		Method method = service.getClass().getMethod(methodName, parameterTypes);
		returnType = method.getReturnType();
		if(!returnType.equals(Void.TYPE)) {
			returnValue = method.invoke(service, parameters);
		} else {
			returnValue = null;
		}
		/** TODO: Exception을 포함하는 기능 만들기 */
	}
	
	public Class<?> getReturnType() {
		return returnType;
	}
	
	public Object getReturnValue() { 
		return returnValue;
	}
}
